package com.jdls.web;

import com.jdls.pojo.User;
import com.jdls.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

/**
 * @author 嘉德罗斯
 * @date 2021/9/4
 */
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8"); // 处理请求参数的乱码
        response.setContentType("text/html;charset=utf-8"); // 处理响应数据的乱码
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String remember = request.getParameter("remember");
        UserService userService = new UserService();
        User user = userService.login(username, password);
        if(user!=null){
            if("1".equals(remember)){
                Cookie c_username = new Cookie("username", username);
                Cookie c_password = new Cookie("password", password);
                Cookie checked = new Cookie("checked", "checked");
                checked.setMaxAge(60*60*24*7);
                c_username.setMaxAge(60*60*24*7);
                c_password.setMaxAge(60*60*24*7);
                response.addCookie(checked);
                response.addCookie(c_username);
                response.addCookie(c_password);
            }
            HttpSession session = request.getSession();
            session.setAttribute("user",user);
            response.sendRedirect("/user/hello.html");
        }else{
            request.setAttribute("msg","用户名或密码错误");
            request.getRequestDispatcher("/Login.jsp").forward(request,response);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
